package com.sy.cloud.wechat.controller;

import com.google.gson.Gson;
import com.sy.cloud.wechat.model.Wxuser;
import com.sy.cloud.wechat.utils.CheckUtil;
import com.sy.common.service.IBaseService;
import com.sy.cloud.wechat.entity.AccessToken;
import com.sy.cloud.wechat.entity.message.AcceptableXmlMessage;
import com.sy.cloud.wechat.entity.message.EventMessage;
import com.sy.cloud.wechat.entity.message.WeChatMessage;
import com.sy.cloud.wechat.entity.message.event.ClickEventMessage;
import com.sy.cloud.wechat.entity.message.event.SubscribeEventMessage;
import com.sy.cloud.wechat.service.ConfigService;
import com.sy.cloud.wechat.service.MessageService;
import com.sy.cloud.wechat.service.WeChatClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhuwenquan on 2017/9/10.
 */
@Controller
@RequestMapping("/wechatapi")
@Slf4j
public class WechatController {
    @Autowired
    private MessageService messageService;

    @Resource
    private WeChatClient clientService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private IBaseService baseService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public
    @ResponseBody
    void index(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // 接收微信服务器以Get请求发送的4个参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");


        if( "".equals( echostr )   ){
            log.info("等于null");
            return;
        }else{
            log.info( "不等于null" );
            response.getWriter().print(echostr);
        }
    }

    @RequestMapping(value = "/index",method = RequestMethod.POST)
    public void receive(HttpServletRequest request,
                        HttpServletResponse response
    ) throws Exception {
        InputStream is = request.getInputStream();
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap = convertXmlToMap(is);


        String openId = resultMap.get("FromUserName");
        String weixinId = resultMap.get("ToUserName");
        Long createTime = Long.valueOf(resultMap.get("CreateTime"));
        WeChatMessage.MsgType msgType = WeChatMessage.MsgType.valueOf(resultMap.get("MsgType"));
        AcceptableXmlMessage message = null;

        Gson gson = new Gson();
        log.info( gson.toJson(resultMap) );



        switch (msgType) {
            case event:
                String event = resultMap.get("Event");
                log.info("event"+event);
                switch (EventMessage.Event.valueOf(event)){
                    case subscribe:
                        SubscribeEventMessage subscribeEventMessage = new SubscribeEventMessage();
                        subscribeEventMessage.setCreateTime( createTime );
                        subscribeEventMessage.setEvent(EventMessage.Event.valueOf(event));
                        subscribeEventMessage.setOpenId(openId);
                        subscribeEventMessage.setWeixinId(weixinId);
                        subscribeEventMessage.setEventKey(resultMap.get("EventKey"));
                        subscribeEventMessage.setTicket(resultMap.get("Ticket"));
                        message = subscribeEventMessage;
                        log.info("调用getWechatUsrz");
                        clientService.getWechatUser(openId,weixinId);
                        break;
                    case CLICK:
                        ClickEventMessage clickEventMessage = new ClickEventMessage();
                        clickEventMessage.setCreateTime(createTime);
                        clickEventMessage.setEvent(EventMessage.Event.valueOf(event));
                        clickEventMessage.setEventKey(resultMap.get("EventKey"));
                        clickEventMessage.setOpenId(openId);
                        clickEventMessage.setWeixinId(weixinId);
                        message = clickEventMessage;
                        log.info("点击事件");
                        log.info(resultMap.get("EventKey"));
                        Date now = new Date();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
                        String in = "<a href='http://gak.tc2stgs.com?open_id="+openId+"'>登录入口</a>";
                        // 根据weixinId搜索token
                        StringBuilder sb = new StringBuilder();
                        sb.append("From Wxuser where wxid ='");
                        sb.append( weixinId );
                        sb.append("'");
                        log.info( sb.toString() );
                        List<Wxuser> wxusers = baseService.listQuery(sb.toString(), Wxuser.class);
                        Wxuser wxuser = wxusers.get(0);
                        if( wxuser != null ){
                            in = "<a href='http://gok.tc2stgs.com?open_id="+openId+"&token="+wxuser.getToken()+"'>登录入口</a>";
                        }
                        log.info("发送的内容"+in+"结束");
                        log.info("微信id"+weixinId);
                        log.info("openId"+openId);


                        /*获取accesstoken*/
                        messageService.sendTextMessage(weixinId,openId,in);
                        log.info("sendTextMessage结束");
                        break;
                    case VIEW:

                        break;
                    case unsubscribe:
                        break;
                }
        }
    }


    public static Map<String, String> convertXmlToMap(InputStream is) {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        // 解析xml，将获取到的返回结果xml进行解析成我们习惯的文字信息
        SAXReader reader = new SAXReader();// 第三方jar:dom4j【百度：saxreader解析xml】
        Document document = null;
        try {
            document = reader.read(is);
        } catch (DocumentException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        // 测试输出
        Set<String> keySet = map.keySet();
        // 测试输出解析后用户发过来的信息
//        log.info("TAG" + "：解析用户发送过来的信息开始");
//        for (String key : keySet) {
//            log.info("\r\n" + key + ":" + map.get(key) + "\r\n");
//        }
//        log.info("TAG" + "：解析用户发送过来的信息结束");
        return map;
    }


}
